package com.odata.springboot.starter.odata.odata.sql.filterMethod.impl;

import com.odata.springboot.starter.odata.odata.sql.filterMethod.FilterMethodHandler;
import com.odata.springboot.starter.odata.odata.sql.filterMethod.FilterMethodHandlerFactory;
import com.odata.springboot.starter.odata.odata.sql.filterMethod.ParseFilterProcess;
import com.odata.springboot.starter.odata.odata.sql.sqlBuild.OdataSqlInformation;
import com.odata.springboot.starter.odata.odata.sql.sqlBuild.SqlSyntaxConstants;
import org.apache.olingo.server.api.uri.queryoption.expression.Expression;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
import org.apache.olingo.server.core.uri.queryoption.expression.MethodImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * like %keyword 的实现
 *
 * @author chenYX
 * @date 2021/6/29 15:53
 * @description
 */
@Component
public class EndswithMethodHandle implements FilterMethodHandler {

    @Autowired
    private ParseFilterProcess parseFilterProcess;

    @Override
    public void handle(MethodImpl methodImpl, OdataSqlInformation.SqlInformationBuild sqlInformationBuild) {
        List<Expression> parameters = methodImpl.getParameters();
        sqlInformationBuild.appendFilter(SqlSyntaxConstants.LEFT_PARENTHESIS);
        Expression expression = parameters.get(0);
        parseFilterProcess.processFilterExpression(expression,sqlInformationBuild);

        //CONCAT('%',?)
        sqlInformationBuild.appendFilter(SqlSyntaxConstants.SPACE)
                .appendFilter(SqlSyntaxConstants.LIKE)
                .appendFilter(SqlSyntaxConstants.SPACE)
                .appendFilter(SqlSyntaxConstants.CONCAT)
                .appendFilter(SqlSyntaxConstants.LEFT_PARENTHESIS)
                .appendFilter(SqlSyntaxConstants.APOSTROPHE)
                .appendFilter(SqlSyntaxConstants.WILDCARD)
                .appendFilter(SqlSyntaxConstants.APOSTROPHE)
                .appendFilter(SqlSyntaxConstants.COMMA_STRING);

        parseFilterProcess.processFilterExpression(parameters.get(1),sqlInformationBuild);
        sqlInformationBuild.appendFilter(SqlSyntaxConstants.RIGHT_PARENTHESIS)
                .appendFilter(SqlSyntaxConstants.RIGHT_PARENTHESIS);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        FilterMethodHandlerFactory.putHandler(MethodKind.ENDSWITH.toString(), this);
    }
}
